package com.yutian.example.demo.common.utils;

import org.slf4j.MDC;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

/**
 * 追踪日志，我们使用%X{userName}来定义此处会打印MDC里面key为userName的value，
 * 如果所定义的字段在MDC不存在对应的key，那么将不会打印，会留一个占位符。
 */
public final class ThreadContext {

    public static String createLogId() {
        return createLogId("CTR-");
    }

    public static String createLogId(String pre) {
        // 嵌入hostname，便于集群部署时定位日志机器
        String hostname = "";
        try {
            InetAddress addr = InetAddress.getLocalHost();
            hostname = addr.getHostName();
        } catch (UnknownHostException e) {
        }
        return new StringBuilder().append(pre).append(hostname).append("-")
                .append(UUID.randomUUID().toString().replace("-", ""))
                .toString();
    }


    public static void putLog(final String value) {
        MDC.put("logId", value);
    }

    public static void removeLog() {
        MDC.remove("logId");
    }

    public static String getLog() {
        return MDC.get("logId");
    }

    public static void clear() {
        MDC.clear();
    }
}